﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Configuration;
using System.Threading;

namespace TY_Hoist.WinApp.Code
{
    /// <summary>
    /// 激光测距传感器
    /// </summary>
    public class LaserRanger : SerialPort
    {
        //定义数据缓存区
        private List<byte> buffer = new List<byte>(4096);
        public static byte[] receivedData;
        public LaserRanger()
        {

            this.PortName = ConfigurationManager.AppSettings["LRComNumber"].ToString();
            this.BaudRate = 9600;
            this.Parity = Parity.None;
            this.DataBits = 8;
            this.StopBits = StopBits.One;
            this.RtsEnable = true;
            this.ReadBufferSize = 1024;
            this.WriteBufferSize = 512;
            this.DtrEnable = true;
            this.ReceivedBytesThreshold = 1;
            this.Encoding = Encoding.GetEncoding("GB2312");

            this.Open();

            this.Start();
           
        }
        /// <summary>
        /// 启动激光测距
        /// </summary>
        public void Start()
        {
           
            this.CmdSend(new byte[] { 0X4F });
            Thread.Sleep(1500);
            this.CmdSend(new byte[] { 0X43 });

            this.DataReceived += LaserRanger_DataReceived;

        }
        public int rrr { get; set; }
        private void LaserRanger_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort cPort = (SerialPort)sender;
            int n = cPort.BytesToRead;
            byte[] c = new byte[n];
            cPort.Read(c, 0, c.Length);
            buffer.AddRange(c);
            receivedData = buffer.ToArray();
            cPort.DiscardInBuffer();
            cPort.DiscardOutBuffer();
            buffer.Clear();
        }
        public double GetValue()
        {
            if (receivedData != null && receivedData.Length==6)
            {
                if (receivedData[2].ToString() == "10")
                {
                    return -1.0;
                }
                return Convert.ToDouble(  receivedData[1].ToString()+ receivedData[2].ToString()+ receivedData[3].ToString()+ receivedData[4].ToString()+ receivedData[5].ToString())/10.0;

            }
            return -1.0;

        }

        /// <summary>
        /// 获取稳定值
        /// </summary>
        /// <returns></returns>
        public double GetStableValue()
        {
            List<double> valueList = new List<double>();
            while (true)
            {
                if (GetValue() != -1.0)
                {
                    valueList.Add(GetValue());
                }

                if (valueList.Count == 3)
                {
                    if (valueList.Max() - valueList.Min() <= 0.5)
                    {
                        return valueList.Last();
                    }
                    else
                    {
                        valueList.RemoveAt(0);
                    }
                }
                Thread.Sleep(500);
            }

        }


        /// <summary>
        /// 停止激光测距
        /// </summary>
        public void Stop()
        {
            this.CmdSend(new byte[] { 0X55 });
        }


        /// <summary>
        /// 发送串口命令
        /// </summary>
        /// <param name="cmd"></param>
        public void CmdSend(byte[] cmd)
        {
            buffer = new List<byte>(4096);
            try
            {
                this.Write(cmd, 0, cmd.Length);

            }
            catch (Exception)
            {

                // throw;
            }

        }
        /// <summary>
        /// 清空缓存命令
        /// </summary>
        public void Clear()
        {
            this.DiscardInBuffer();
            this.DiscardOutBuffer();
            buffer.Clear();

        }
        /// <summary>
        /// 释放串口
        /// </summary>
        public new void Dispose()
        {
            if (this.IsOpen)
            {
                this.Close();
            }
            this.Dispose(true);
        }
    }
}
